<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="app">
        <h1 id="counter"></h1>
        <!-- <h1>{{counter}}</h1> -->
        <button onclick="getCounter()">get</button>
        <button onclick="setCounter()">set</button>
        <button onclick="getAsyncCounter()">asyncGet</button>
    </div>
</body>
<script>
    //创建一个仓库 仓库管理员 
    //mutations 同步  actions 异步
    // state 货物
    let store = {
        state: {
            counter: 11
        },
        //样式通用
        commit: function(fnName) {
            this.mutations[fnName](this.state);
        },
        //取出操作异步的行为 dispatch
        dispatch: function(fnName) {
            //this=>state
            this.actions[fnName](this);
        },
        //同步
        mutations: {
            getCounter: function(state) {
                console.log(state);
                state.counter--;
            },
            setCounter: function(state) {
                state.counter++;
            }
        },
        //异步
        actions: {
            getAsyncCounter: function({
                state
            }) {
                setTimeout(function() {
                    state.counter++;
                    init();
                }, 2000)
            }
        }
    };

    function init() {
        document.getElementById("counter").innerHTML = store.state.counter;
    };

    function getCounter() {
        store.commit("getCounter");
        init();
    };

    function setCounter() {
        store.commit("setCounter");
        init();
    };

    function getAsyncCounter() {
        store.dispatch("getAsyncCounter");
        init();
    }
    init();
</script>

</html>